package com.ipay.wechat.core;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.jdom.CDATA;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

import com.ipay.utils.StringUtil;

public class WechatParam extends LinkedHashMap<String, String> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 495499677091491001L;
	
	public static WechatParam create(){
		return new WechatParam();
	}

	public String toXML() throws IOException{
		Document doc = new Document();
		Element xml = new Element("xml");
		doc.setRootElement(xml);
		Iterator<Map.Entry<String, String>> it = this.entrySet().iterator();
		while(it.hasNext()){
			Map.Entry<String,String> m = it.next();
			String key = m.getKey();
			String value = m.getValue();
			if(StringUtil.isEmpty(key)){ continue;}
			Element item = new Element(key);
			item.addContent(new CDATA(value));
			xml.addContent(item);
		}
		/*for(String key : this.keySet()) {
			if(StringUtil.isEmpty(key)){ continue;}
			Element item = new Element(key);
			item.addContent(new CDATA(this.get(key)));
			xml.addContent(item);
		}*/
		XMLOutputter xmlout = new XMLOutputter();
		ByteArrayOutputStream bo = new ByteArrayOutputStream();     
        xmlout.output(doc, bo);
		String s = bo.toString("UTF-8");
        bo.close();
		return s;
	}
	
	public static void main(String[] args) throws IOException {
		WechatParam param = WechatParam.create();
		param.put("ToUserName", "toUser");
		param.put("FromUserName", "fromUser");
		param.put("CreateTime", "1348831860");
		param.put("MsgType", "text");
		param.put("Content", "this is a test");
		param.put("MsgId", "1234567890123456");
		System.out.println(param.toXML());
	}
}
